from django.contrib.auth import get_user_model
from rest_framework import serializers
from rest_registration.utils.users import get_user_field_names


def get_user_perms(user):
    all_perms = user.get_all_permissions()
    sso_perms = [
        perm.split(".")[1] for perm in all_perms if perm.split(".")[0] == "main"
    ]
    return ",".join(sso_perms)


class MetaObj:
    pass


class UserProfileSerializer(serializers.ModelSerializer):

    limit = serializers.SerializerMethodField()

    def get_limit(self, obj):
        return get_user_perms(obj)

    def __init__(self, *args, **kwargs):
        user_class = get_user_model()
        field_names = list(get_user_field_names()) + ["limit"]
        read_only_field_names = get_user_field_names(non_editable=True)
        meta_obj = MetaObj()
        meta_obj.model = user_class
        meta_obj.fields = field_names
        meta_obj.read_only_fields = read_only_field_names
        self.Meta = meta_obj  # pylint: disable=invalid-name
        super().__init__(*args, **kwargs)
